package com.zj.z11select.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zj.z11select.entity.User;
import com.zj.z11select.exception.CustomException;
import com.zj.z11select.mapper.UserMapper;
import com.zj.z11select.secruity.domian.LoginBody;
import com.zj.z11select.secruity.domian.LoginUser;
import com.zj.z11select.secruity.service.TokenService;
import com.zj.z11select.service.UserService;
import com.zj.z11select.utils.MD5Utils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * <p>
 * 用户信息表  服务实现类
 * </p>
 *
 * @author ZHOUJIE
 * @since 2021-07-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private TokenService tokenService;

    @Resource
    private UserMapper userMapper;


    @Override
    public LoginUser login(LoginBody loginBody) {
        User user = userMapper.selectUserByUserName(loginBody.getUsername());
        Assert.notNull(user,"用户名不存在");
        if (StringUtils.equals(MD5Utils.md5(loginBody.getPassword()),user.getPassword())){
            LoginUser loginUser = new LoginUser(user);
            loginUser.setToken(tokenService.createToken(loginUser));
            return loginUser;
        }
        throw new CustomException("密码错误");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public User register(String username, String password) {
        Assert.notNull(username,"用户名不能为空");
        Assert.notNull(password,"密码不能为空");
        //spring 默认是单例，可直接用this充当锁
        synchronized(this){
            //查询当前用户名是否已经被注册
            User user = this.userMapper.selectUserByUserName(username);
            if (ObjectUtils.isEmpty(user)){
                user = new User(username,MD5Utils.md5(password));
                if (this.userMapper.insert(user) > 0){
                    return this.userMapper.selectUserById(user.getUserId());
                }
            }
            return null;
        }
    }


    @Override
    public boolean checkUser(String username) {
        User user = this.baseMapper.selectUserByUserName(username);
        return user != null;
    }
}
